<template>
  <div id='wrap'>
    <h1>侦听器watch</h1>
    <button @click="count++">增加:{{ count }}</button>
    <hr>
    <button @click="add">增加：{{ `${x}:${y}` }}</button>
    <hr>
    <button>求和:{{ sum() }}</button>
    <button @click="name='123'">改变name</button>
    <hr>
    <button @click="user1.details.age++">改变age：{{ user1.details.age }}</button>
    <hr>
    <button @click="message='123'">改变message：{{ message }}</button>
    <hr>
    <button @click="value++">改变value：{{ value }}</button>
  </div>
</template>

<script lang='ts'>
export default {
  name: 'scu14',
}
</script>

<script lang='ts' setup>
import { ref,watch,reactive } from 'vue'
const count=ref(0)
watch(count,(newValue,oldValue)=>{
    console.log(`count响应式变量改变从${newValue}到${oldValue}`);
})
const x=ref(0)
const y=ref(0)
const add=()=>{
    x.value++
    y.value++
}
watch(
    [x,y],
    ([newX,newY],[oldX,oldY])=>{
        console.log(`x响应式变量改变从${newX}到${oldX},y响应式变量改变从${newY}到${oldY}`);
    }
)
const sum=()=>{
    const sums=x.value + y.value
    return sums
}
watch(sum,(newValue,oldValue)=>{
    console.log(`sum响应式变量改变从${newValue}到${oldValue}`);
})
const name=ref('Alice')
watch(
    ()=>name.value.length,
    (newLength,oldLength)=>{
        console.log(`Name length changed from ${oldLength} to ${newLength}`);        
    }
)
const user1=reactive({
    name:'Alice',
    details:{
        age:25,
        hobbies:['reading','coding']
    }
})
watch(user1,(newValue,oldValue)=>{
    console.log(`user1响应式变量改变${newValue.details.age}`);
},
{deep:true}
)
const message=ref('hello')
watch(message,(newValue,oldValue)=>{
    console.log(`message响应式变量改变从${oldValue}到${newValue}`);
},
// {immediate:true}
)
const value=ref(0)
watch(value,(newVal)=>{
    setTimeout(()=>{
        console.log('在DOM更新之前触发',newVal);
    },2000)
},{flush:'pre'}
)
watch(
    value,
    (newVal)=>{
        setTimeout(()=>{
             console.log('在DOM更新之后触发',newVal)
        },2000)
    },
    {flush:'post'}
)
watch(
    value,
    (newVal)=>{
        setTimeout(()=>{
             console.log('同步触发',newVal)
        },2000)
    },
    {flush:'sync'}
)
</script>
<style scoped lang='scss'>

</style>